﻿#include"test917.h"
#include"room.h"
#include<json\rapidjson.h>
#include<json\document.h>
#include"CommonFunction.h"
#pragma execution_character_set("utf-8")
using namespace std;
Scene *test917::createscene()
{
	return test917::create();
}
bool test917::init()
{
	if (!Scene::init())
	{
		return false;
	}

	//加载素材
	SpriteFrameCache::getInstance()->addSpriteFramesWithFile("GameSence.plist", "GameSence.png");

	//注册触屏事件
	//事件监听器
	EventListenerTouchOneByOne *listener = EventListenerTouchOneByOne::create();
	listener->onTouchMoved = CC_CALLBACK_2(test917::onTouchMoved, this);
	listener->onTouchBegan = CC_CALLBACK_2(test917::onTouchBegin, this);
	//把这个listener加入到事件派发器里
	Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);

	CommonFunction::getChineseWithKey("b");

	Size visibleSize = Director::getInstance()->getVisibleSize();
	//游戏背景
	Sprite *background = Sprite::create("Background.png");
	background->setPosition(visibleSize.width / 2, visibleSize.height / 2);
	addChild(background);


	//出牌按钮
	Sprite *discard_normal = Sprite::createWithSpriteFrameName("youxi13.png");
	Sprite *discard_selected = Sprite::createWithSpriteFrameName("youxi13.png");
	Sprite *discard_disabled = Sprite::createWithSpriteFrameName("youxi18.png");
	
	MenuItemSprite *discardItem = MenuItemSprite::create(discard_normal, discard_selected, discard_disabled, CC_CALLBACK_1(test917::judgeItemChicked, this));
	discardItem->setScale(0.5);
	discardItem->setPositionY(-50);
	discardItem->setVisible(false);
	discardItem->setTag(1);
	//提示按钮
	Sprite *suggestItem_normal = Sprite::createWithSpriteFrameName("youxi12.png");
	Sprite *suggestItem_selected = Sprite::createWithSpriteFrameName("youxi12.png");
	MenuItemSprite * suggestItem = MenuItemSprite::create(suggestItem_normal, suggestItem_selected, CC_CALLBACK_1(test917::suggestItemClicked, this));
	suggestItem->setScale(0.5);
	suggestItem->setPositionY(-50);
	suggestItem->setPositionX(180);
	suggestItem->setVisible(false);
	suggestItem->setTag(2);

	Button *beginButton = Button::create("begin_normal.png");
	beginButton->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2 - 50));
	beginButton->setScale(0.8);
	beginButton->addTouchEventListener(CC_CALLBACK_2(test917::beginGame, this));
	addChild(beginButton);


	//返回
	MenuItemImage *closeItem = MenuItemImage::create("CloseNormal.png", "CloseSelected.png");
	closeItem->setCallback(CC_CALLBACK_1(test917::closeGameScene, this));
	closeItem->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT);
	closeItem->setPosition(Vec2(-visibleSize.width / 2, visibleSize.height / 2));
	closeItem->setScale(3);

	Menu *menu = Menu::create(closeItem, discardItem, suggestItem, NULL);
	menu->setTag(300);
	addChild(menu);
	//创建自己
	self_pos = 3;
	for (int i = 1; i <= 4; i++)
	{
		Player *player = new Player();
		player->account = StringUtils::format("player%d", i);
		player->position = i;
		if (i == 1)
		{
			player->headImgUrl = "http://thirdwx.qlogo.cn/mmopen/4JLXvFlrVwt1nZrRricjsNLsx9e4LtWFgH9vteWnlEITgDH9wEpss1Uzb7mBr5tSoJOOgAT1EJdoWbuzwjxtGWDHXlk1GG7Pk/132";
		}
		else if (i == 2)
		{
			player->headImgUrl = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1538159805298&di=1abfa9cb60c462eea7098002533e511e&imgtype=jpg&src=http%3A%2F%2Fimg2.imgtn.bdimg.com%2Fit%2Fu%3D3066218837%2C3930892372%26fm%3D214%26gp%3D0.jpg";
		}
		else if (i == 3)
		{
			player->headImgUrl = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1538159759212&di=400e79dbf6f45f08f853ca0dd4112a63&imgtype=0&src=http%3A%2F%2Fpic.kekenet.com%2F2017%2F0323%2F24621490236152.png";
		}
		else if (i == 4)
		{
			player->headImgUrl = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1538159759212&di=9784cc7df029af4032b9d56108e5df5a&imgtype=0&src=http%3A%2F%2Fwww.goumin.com%2Fattachments%2Fphoto%2F0%2F0%2F69%2F17866%2F4573921.jpg";
		}

		loadPlayerUI(player);


	}

	//创建按钮
	Button *showButton = Button::create("show_normal.png");
	showButton->setPosition(Vec2(visibleSize.width / 2 - 100, visibleSize.height / 2 - 50));
	showButton->setVisible(false);//隐藏
	showButton->setTag(100);
	showButton->setScale(0.8);
	showButton->addTouchEventListener(CC_CALLBACK_2(test917::buttonClicked, this));

	addChild(showButton);

	//创建不晒红十
	Button *unShowButton = Button::create("unShow_normal.png");
	unShowButton->setPosition(Vec2(visibleSize.width / 2 + 100, visibleSize.height / 2 - 50));
	unShowButton->setVisible(false);//隐藏
	unShowButton->setTag(200);
	unShowButton->setScale(0.8);
	unShowButton->addTouchEventListener(CC_CALLBACK_2(test917::buttonClicked, this));
	addChild(unShowButton);

	return true;
}
void test917::beginGame(Ref *pSender, Widget::TouchEventType type)
{
	Size visibleSize = Director::getInstance()->getVisibleSize();
	if (type != Widget::TouchEventType::ENDED)
	{
		return;
	}
	//如果之前有牌，清除后再开始
	if (game)
	{
		//因为game创建的时候，在构造器里创建了存放自己的节点
		game->selfCards_node->removeAllChildrenWithCleanup(true);
		CC_SAFE_DELETE(game);
		log("a");
		//之前的一些残留的内容需清除
		player_self->node->removeChildByTag(2);

	}
	//隐藏开始按钮
	Button *btn = (Button *)pSender;
	btn->setVisible(false);

	log("游戏开始～～～");
	// 1.洗牌
	int cards[54];
	game = CardGame::getInstance();
	game->shuffle(cards, 54);
	game->gameDidBegan = true;

	// 2.发牌
	player_self->initCards();
	player_right->initCards();
	player_front->initCards();
	player_left->initCards();
	Player *currentPlayer; // 记录当前操作的玩家
	int start_pos = 3; // 先发给3号
	for (int i = 0; i < 54; i++) {
		// 获取当前发牌者的真实位置
		char pos_char = getPlayerCharPosition((start_pos + i - 1) % 4 + 1);

		// ♥️3
		if (cards[i] == 41) {
			game->first = pos_char;
		}
		// ♦️10
		if (cards[i] == 22) {
			game->red10_fk = pos_char;
		}
		// ♥️10
		if (cards[i] == 48) {
			game->red10_hx = pos_char;
		}

		switch (pos_char) {
		case 's':
			currentPlayer = player_self;
			break;
		case 'r':
			currentPlayer = player_right;
			break;
		case 'f':
			currentPlayer = player_front;
			break;
		case 'l':
			currentPlayer = player_left;
			break;
		default:
			break;
		}

		currentPlayer->cards[currentPlayer->countCards()] = cards[i];
	}

	//发牌结束位置
	player_self->showCardsCount();
	player_right->showCardsCount();
	player_left->showCardsCount();
	player_front->showCardsCount();


	//如果至少有一张红十在我自己这里，那需要显示晒不晒的按钮
	if (game->red10_fk == 's' || game->red10_hx == 's')
	{
		getChildByTag(100)->setVisible(true);
		getChildByTag(200)->setVisible(true);
	}
	else
	{
		getChildByTag(100)->setVisible(false);
		getChildByTag(200)->setVisible(false);

		getChildByTag(300)->getChildByTag(1)->setVisible(true);
		getChildByTag(300)->getChildByTag(2)->setVisible(true);
	}
	//模拟自己的手牌
	/*int test[] = { 22,48,9,45,23,-1,-1,-1,-1,-1,-1,-1,-1,-1};
	for (int i = 0; i < 14; i++)
	{
		player_self->cards[i] = test[i];
	}*/
	//给自己牌排序
	player_self->sortCards();
	//计算牌组放置的整体X轴居中位置
	int count = player_self->countCards();
	int mid = count / 2;
	float midx = (visibleSize.width + 180) / 2;

	// 显示自己的牌
	for (int i = 0; i < player_self->countCards(); i++) {

		Sprite *cardSprite = game->getCardSpriteWithValue(player_self->cards[i]);
		cardSprite->setScale(0.9);
		cardSprite->setPosition(Vec2(midx + 60 * (i - mid) + (count % 2 == 0 ? 30 : 0), cardSprite->getBoundingBox().size.height / 2 + 30));

		cardOriginY = cardSprite->getPositionY();

		game->selfCards_node->addChild(cardSprite);
	}
	addChild(game->selfCards_node);
}

void test917::setRoomId(int roomId)
{
	Label *label = Label::createWithSystemFont(StringUtils::format("room id=%d", roomId + 1), "Arial", 40);
	Size visibleSize = Director::getInstance()->getVisibleSize();
	label->setAnchorPoint(Vec2::ANCHOR_TOP_RIGHT);
	label->setPosition(Vec2(visibleSize.width - 30, visibleSize.height - 30));
	label->enableOutline(Color4B(90, 221, 247, 255), 3);

	addChild(label);

}
void test917::closeGameScene(Ref *pSender)
{
	CardGame::cleanInstance();
	Director::getInstance()->replaceScene(room::createScene());
}
////加载对应玩家的UI信息
char test917::getPlayerCharPosition(int pos)
{
	if (self_pos == 1)//当自己坐在1
	{
		if (pos == 2)return'r';//2在右边
		if (pos == 3)return'f';//3在对面
		if (pos == 4)return'l';//4在左边 
	}
	else if (self_pos == 2)//当自己坐在2上
	{
		if (pos == 1)return'l';//1在左边
		if (pos == 3)return'r';//3在右边
		if (pos == 4)return'f';//4在对面
	}
	else if (self_pos == 3)//当自己坐在3上
	{
		if (pos == 1)return'f';//1在对面
		if (pos == 2)return'l';//3在左边
		if (pos == 4)return'r';//4在右边
	}
	else if (self_pos == 4)//当自己坐在4上
	{
		if (pos == 1)return'r';//1在右边
		if (pos == 2)return'f';//3在对面
		if (pos == 3)return'l';//4在左边
	}
	return's';//以上都不满足，则是自己
}
void test917::loadPlayerUI(Player *player)
{
	//将int的椅子号，转化为相对我所在的位置
	char pos_char1 = getPlayerCharPosition(player->position);
	log("%c", pos_char1);

	player->pos_char = pos_char1;

	player->createPlayerNode();
	addChild(player->node);

	switch (player->pos_char)
	{
	case's':
		player_self = player;
		break;
	case'r':
		player_right = player;
		break;
	case'f':
		player_front = player;
		break;
	case'l':
		player_left = player;
		break;
	}

}

bool test917::onTouchBegin(Touch *touch, Event *event)
{
	//获取点击位置
	Vec2 point = touch->getLocation();

	if (!game || game->gameDidBegan == false)
	{
		return true;
	}

	//遍历牌
	int count = player_self->countCards();
	bool didTouchCard = false;

	for (int i = 0; i < count; i++)
	{
		//获取当前遍历的那张牌的节点
		Node *card_node = game->selfCards_node->getChildByTag(player_self->cards[i]);

		//获取该节点的Rect
		Rect rect = card_node->getBoundingBox();

		//计算左侧区域
		Rect rectFortouch = Rect(rect.origin.x, rect.origin.y, 60, rect.size.height);

		//最后一张，接收事件的范围应该是整个区域
		if (i == count - 1)
		{
			rectFortouch = rect;
		}

		//如果区域内包含了点击的点的位置，则找到了那张被点击的牌
		if (rectFortouch.containsPoint(point))
		{
			if (card_node->getPositionY() > cardOriginY)
			{
				card_node->setPositionY(cardOriginY);
			}
			else
			{
				card_node->setPositionY(cardOriginY + 30);
			}
			didTouchCard = true;
			break;
		}
	}

	if (didTouchCard)
	{
		log("1");
	}
	else
	{
		for (int i = 0; i < count; i++)
		{
			//找到牌，并缩进
			Node *cars_node = game->selfCards_node->getChildByTag(player_self->cards[i]);
			cars_node->setPositionY(cardOriginY);
		}
	}
	return true;
}

void test917::onTouchMoved(Touch *touch, Event *event)
{
	Vec2 point = touch->getLocation();
	if (!game || game->gameDidBegan == false)
	{
		return;
	}

	//遍历牌
	int count = player_self->countCards();
	for (int i = 0; i < count; i++)
	{
		//获取当前遍历的那张牌的节点
		Node *card_node = game->selfCards_node->getChildByTag(player_self->cards[i]);

		//获取该节点的Rect
		Rect rect = card_node->getBoundingBox();

		//计算左侧区域
		Rect rectFortouch = Rect(rect.origin.x, rect.origin.y, 60, rect.size.height);

		//最后一张，接收事件的范围应该是整个区域
		if (i == count - 1)
		{
			rectFortouch = rect;
		}

		//如果区域内包含了点击的点的位置，则找到了那张被点击的牌
		if (rectFortouch.containsPoint(point))
		{
			card_node->setPositionY(cardOriginY + 30);
			break;

		}
	}

}
void test917::buttonClicked(Ref *pSender, Widget::TouchEventType type)
{
	//处理结束事件
	if (type == Widget::TouchEventType::ENDED)
	{
		Button *btn = (Button *)pSender;
		switch (btn->getTag())
		{
		case 100:
		{
			int res = 0;
			if (game->red10_fk == 's'&&game->red10_hx == 's')
			{
				res = 3;
			}
			else if (game->red10_fk == 's')
			{
				res = 1;
			}
			else if (game->red10_hx == 's')
			{
				res = 2;
			}
			player_self->show(res);
			player_front->show(res);
			player_right->show(res);
			player_left->show(res);
			break;
		}
		case 200:

			break;
		default:
			break;
		}
		getChildByTag(100)->setVisible(false);
		getChildByTag(200)->setVisible(false);
		getChildByTag(300)->getChildByTag(1)->setVisible(true);
		getChildByTag(300)->getChildByTag(2)->setVisible(true);
	}
}
void test917::suggestItemClicked(Ref * sender)
{
	//测试模拟上家出牌
	//1. 模拟单牌
	vector<int> arr = { 52,53 };
	player_left->discard(arr, PokerType::POKER_TYPE_SINGLE);
	log("提示按钮被点击");
	//2. 提示
	vector<int> suggestResult =  game->suggest(player_self->cards, player_self->countCards(), arr);
	if (suggestResult.size() == 0) {
		log("没有找到更大的单牌");
	}
	else {
		log("找到更大的单牌:%d", suggestResult[0]);
		//先把所有牌缩回
		for (int i = 0; i < player_self->countCards(); i++)
		{
			Node *card = game->selfCards_node->getChildByTag(player_self->cards[i]);
			card->setPositionY(cardOriginY);
		}
		//遍历提示的vector ,把对应的牌弹出
		for (int i = 0; i < suggestResult.size(); i++)
		{
			Node *card = game->selfCards_node->getChildByTag(suggestResult[i]);
			card->setPositionY(cardOriginY + 30);
		}
	}
}
void test917::judgeItemChicked(Ref *pSender)
{
	//首先获取选择的牌是什么
	vector<int> arr;
	//遍历一遍牌的精灵，看看哪些牌弹出了
	for (int i = 0; i < player_self->countCards(); i++)
	{
		Node *card_node = game->selfCards_node->getChildByTag(player_self->cards[i]);
		if (card_node->getPositionY() > cardOriginY)
		{
			arr.push_back(player_self->cards[i]);
		}
	}
	PokerType type = game->getPokerTypeWithCards(arr);

	switch (type)
	{
	case POKER_TYPE_SINGLE:
		log("单牌");
		break;
	case POKER_TYPE_KING_BOMB:
		log("王炸");
		break;
	case POKER_TYPE_REDTEN_BOMB:
		log("红十炸弹");
		break;
	case POKER_TYPE_DOUBLE:
		log("对子");
		break;
	case POKER_TYPE_THREE_BOMB:
		log("三张炸弹");
		break;
	case POKER_TYPE_FOUR_BOMB:
		log("四张炸弹");
		break;
	case POKER_TYPE_STRAIGHT:
		log("顺子");
		break;
	default:
		log("牌型有误");
		break;
	}

	if (type > 0)
	{
		//玩家手牌;plaer_self->cards[]
		//出的牌;arr

		//从玩家手牌里移除的牌
		player_self->discard(arr,type);
		/*player_left->discard(arr, type);
		player_right->discard(arr, type);
		player_front->discard(arr, type);*/
	}

	//检验
	for (int i = 0; i < arr.size(); i++)
	{
		log("%d", arr[i]);
	}
}

